package com.project.common.controller;

import com.alibaba.fastjson.JSONObject;
import com.project.common.entity.SysRoleAuthorization;
import com.project.common.service.SysRoleAuthorizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/sysRoleAuthorization")
public class SysRoleAuthorizationController {
    @Autowired
    private SysRoleAuthorizationService sysRoleAuthorizationService;

    @PostMapping("/grantAndRevokeAuthorizationFromRole.action")
    public int grantAndRevokeAuthorizationFromRole(String sysAuthorizationIdsStr,Integer roleId,String sysAuthorizationIdsNoCheck){
        Integer[] sysAuthorizationIds = JSONObject.parseObject(sysAuthorizationIdsStr, Integer[].class);
        Integer[] sysAuthorizationNoCheckIds = JSONObject.parseObject(sysAuthorizationIdsNoCheck, Integer[].class);
        System.out.println(Arrays.toString(sysAuthorizationIds));
        System.out.println(Arrays.toString(sysAuthorizationNoCheckIds));
        if(sysAuthorizationNoCheckIds!=null){
            for(int i=0;i<sysAuthorizationNoCheckIds.length;i++) {
                sysRoleAuthorizationService.deleteByRoleIdAndAuId(roleId,sysAuthorizationNoCheckIds[i]);
            }
        }
        if(sysAuthorizationIds!=null){
            for(int i=0;i<sysAuthorizationIds.length;i++){
                List<SysRoleAuthorization> sysRoleAuthorizations = sysRoleAuthorizationService.selectByRoleIdAndAuId(roleId, sysAuthorizationIds[i]);
                if(sysRoleAuthorizations.size()<=0){

                    SysRoleAuthorization sysRoleAuthorization = new SysRoleAuthorization();
                    sysRoleAuthorization.setAuId(sysAuthorizationIds[i]);
                    sysRoleAuthorization.setRoleId(roleId);
                    sysRoleAuthorizationService.insertSelective(sysRoleAuthorization);
                }
            }
        }

        return 0;
    }
}
